/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiof.moraa.server.service;

import com.hiof.moraa.mapping.TblAthlete;
import com.hiof.moraa.server.dao.AthleteDAO;
import com.hiof.moraa.server.dao.AthleteLiveMediaDAO;
import com.hiof.moraa.server.service.model.LiveMediaFeed;
import com.hiof.moraa.server.service.model.TypeOfAttendant;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Bergy
 */
@Transactional(readOnly = false)
public class AthleteLiveMediaServiceImp extends LiveMediaService {

    AthleteLiveMediaDAO dao;
    AthleteDAO athleteDAO;
    MessageDeliveryService messageDeliveryService;

    public void setMessageDeliveryService(MessageDeliveryService messageDeliveryService) {
        this.messageDeliveryService = messageDeliveryService;
    }

    public void setDao(AthleteLiveMediaDAO dao) {
        this.dao = dao;
    }

    public void setAthleteDAO(AthleteDAO athleteDAO) {
        this.athleteDAO = athleteDAO;
    }

    @Override
    public LiveMediaFeed processLiveMedia(int userId, int athleteId, MultipartFile file, double lat, double lng, double heigh, ServletContext servletContext) {
        TblAthlete athlete = athleteDAO.getAthleteById(athleteId);
        String username = athlete.getTblUser().getUsername();
        String routeName = athlete.getTblRoute().getName();
        String relativePath = getRelativeFilePath(username, routeName, file);
        String absolutePath = getFilePathService().getAbsolutePath(relativePath, servletContext);

        try {
            writeFile(absolutePath, file);
        } catch (IOException ex) {
            Logger.getLogger(AthleteLiveMediaServiceImp.class.getName()).log(Level.SEVERE, null, ex);
        }

        LiveMediaFeed liveMediaFeed = dao.insertAthleteLiveMediaFeed(athleteId, getFilePathService().getResourcePath(relativePath), lat, lng, heigh, new Timestamp(new java.util.Date().getTime()));

        messageDeliveryService.deliveryLiveMediaMessage(userId, TypeOfAttendant.ATHLETE, athleteId, liveMediaFeed);

        return liveMediaFeed;
    }
}
